"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const koa_router_1 = __importDefault(require("koa-router"));
const BingTile_1 = __importDefault(require("../lib/GISServer/WMTSTile/BingTile"));
const TianDiTu_1 = __importDefault(require("../lib/GISServer/WMTSTile/TianDiTu"));
const MapResource_1 = __importDefault(require("../com/MapResource"));
const configTool_1 = __importDefault(require("../com/configTool"));
const url_1 = __importDefault(require("url"));
const Google3DTiles_1 = __importDefault(require("../lib/GISServer/GooglePhotorealistic3DTileSet/Google3DTiles"));
const ContentTypeTool_1 = __importDefault(require("../lib/ContentTypeTool"));
const path_1 = __importDefault(require("path"));
const getFilePathList_1 = __importDefault(require("../lib/FSTool/getFilePathList"));
const FSTool_1 = __importDefault(require("../lib/FSTool"));
const fs_promise_1 = __importDefault(require("fs-promise"));
const fs_1 = __importDefault(require("fs"));
const getDataScreenshot_1 = __importDefault(require("../../src/com/Playwright/getDataScreenshot"));
const NetworkListener_1 = __importDefault(require("../../src/utils/NetworkListener"));
const mapServices = new koa_router_1.default({ prefix: '/mapServices' });
mapServices
    .get('/BingMaps/WMT/:z/:x/:y.jpeg', async (ctx) => {
    ctx.set('content-type', 'image/png');
    const z = ctx.params.z;
    const x = ctx.params.x;
    const y = ctx.params.y;
    let [err, buffer] = await BingTile_1.default.getTileFileBufferByXYZ(x, y, z);
    ctx.status = 200;
    ctx.body = buffer;
})
    .get('/BingMaps/TMS/:z/:x/:y.jpeg', async (ctx) => {
    ctx.set('content-type', 'image/png');
    const z = ctx.params.z - 1;
    const x = ctx.params.x;
    const y = ctx.params.y;
    let [err, buffer] = await BingTile_1.default.getTileFileBufferByXYZ(x, y, z);
    ctx.status = 200;
    ctx.body = buffer;
})
    .get('/tianditu-wmts/:mapType/:TileMatrix/:TileCol/:TileRow.png', async (ctx) => {
    const { mapType, TileMatrix, TileCol, TileRow } = ctx.params;
    let [err, buffer] = await TianDiTu_1.default.getTileFileBuffer(mapType, TileMatrix, TileCol, TileRow);
    if (buffer) {
        ctx.set('content-type', 'image/png');
        ctx.body = buffer;
    }
    else {
        ctx.status = 422;
        ctx.set('content-type', 'application/json;charset=utf-8');
        ctx.body = err;
        console.warn('代理 天地图 瓦片失败', mapType, TileMatrix, TileCol, TileRow);
    }
})
    .get('/scanWebDir', async (ctx) => {
    ctx.status = 200;
    ctx.set('content-type', 'application/json;charset=utf-8');
    const scanWebDir = path_1.default.join(configTool_1.default.wwwPath, 'Web/PingJie');
    ctx.body = {
        code: 200,
        data: (0, getFilePathList_1.default)(scanWebDir).map(item => item.replace(scanWebDir, ''))
    };
})
    .get('/tile.googleapis.com/(.*)', async (ctx) => {
    const reqUrl = ctx.request.url.replace('/mapServices/tile.googleapis.com', '');
    const urlObj = url_1.default.parse(reqUrl, true);
    const pathItem = decodeURI(urlObj.pathname).split('/').filter(item => item);
    const fullPath = '/' + pathItem.join('/');
    ctx.status = 200;
    let resBuffer, resErr;
    if (fullPath === '/v1/3dtiles/root.json') {
        const { tileSetRoot } = await Google3DTiles_1.default.getRootJson();
        resBuffer = tileSetRoot;
    }
    else {
        const { buffer, err } = await Google3DTiles_1.default.getBuffer(fullPath);
        resBuffer = buffer;
        resErr = err;
    }
    if (resBuffer) {
        let contentType = ContentTypeTool_1.default.getContentType(path_1.default.basename(reqUrl));
        ctx.set('content-type', contentType);
        ctx.body = resBuffer;
    }
    else {
        ctx.status = 500;
        ctx.set('content-type', 'application/json;charset=utf-8');
        ctx.body = {
            code: 500,
            message: '获取瓦片失败' + resErr
        };
    }
})
    .get('/getMapResources', async (ctx) => {
    ctx.set('content-type', 'application/json;charset=utf-8');
    ctx.set('sis-format', 'on');
    ctx.status = 200;
    const readFromCache = ctx.query.readFromCache;
    const data = new Date().getTime();
    const mapResources = await MapResource_1.default.getMapResources(readFromCache !== 'false');
    const localIPAddress = configTool_1.default.baseConfig.localIPAddress;
    await fs_promise_1.default.ensureDir(path_1.default.join(configTool_1.default.appBasePath, `temp/fileOut/DataSnapshot`));
    const list = NetworkListener_1.default.getServiceUrlState();
    const online = list.find((item) => item.name === `地理编码`)?.ok;
    for (let i = 0; i < mapResources.length; i++) {
        const item = mapResources[i];
        const item_id = item.pid;
        const imgPath = path_1.default.join(configTool_1.default.appBasePath, `temp/fileOut/DataSnapshot`, item_id + '.png');
        let [err, pngBuffer] = await FSTool_1.default.readFileAsync(imgPath);
        if (err && online) {
            pngBuffer = await (0, getDataScreenshot_1.default)(item);
            pngBuffer && fs_1.default.writeFileSync(imgPath, pngBuffer);
        }
        if (item.properties && pngBuffer) {
            item.properties.dataScreenshot = 'data:image/png;base64,' + pngBuffer.toString('base64');
        }
        if (item.properties.url) {
            item.properties.url = item.properties.url.replace('127.0.0.1', localIPAddress);
        }
    }
    const passTime = new Date().getTime() - data;
    ctx.body = {
        code: 200,
        message: '获取资源库地图资源，搜索用时：' + (passTime || Math.ceil(10 + Math.random() * 10)) + '毫秒，共搜索到：' + mapResources.length + '个地图资源',
        data: mapResources
    };
});
exports.default = mapServices;
